<template>
    <div>
        <layout-box one="权限控制" two="角色列表">
            <!-- 添加按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary">添加角色</el-button>
                </el-col>
            </el-row>
            <br>
            <!-- 表格区域 -->
            <el-table :data="rolelist" border="" stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- 渲染一级权限 -->
                        <!-- el-row表示一行 -->
                        <el-row
                            :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                            v-for="(item,i1) in scope.row.children"
                            :key="item.id"
                        >
                            <!-- 表示一列 -->
                            <el-col :span="5">
                                <el-tag
                                    closable
                                    @close="removeRightById(scope.row,item.id)"
                                    type="primary"
                                >{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 第二列 二级权限 -->
                            <el-col :span="19">
                                <el-row
                                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                                    v-for="(item2,i2) in item.children"
                                    :key="item2.id"
                                >
                                    <el-col :span="6">
                                        <el-tag
                                            closable
                                            @close="removeRightById(scope.row,item2.id)"
                                            type="warning"
                                        >{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 三级权限 -->
                                    <el-col :span="18">
                                        <el-tag
                                            closable
                                            @close="removeRightById(scope.row,item3.id)"
                                            type="danger"
                                            v-for="item3 in item2.children"
                                            :key="item3.id"
                                        >{{ item3.authName }}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="描述"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" icon="el-icon-edit" type="primary">编辑</el-button>
                        <el-button size="mini" icon="el-icon-delete" type="danger">删除</el-button>
                        <el-button
                            size="mini"
                            icon="el-icon-setting"
                            type="warning"
                            @click="showSettingRight(scope.row)"
                        >分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </layout-box>
        <!-- 分配权限的对话框 -->
        <el-dialog title="提示" :visible.sync="rightsDialogVisible"
        @close = "resetDefKeys"
        >
            <el-tree
                :data="rightslist"
                :props="treeProps"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys="defKeys"
                ref="rightTreeRef"
            ></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rightsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="settingRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      rolelist: [],
      rightslist: [],
      rightsDialogVisible: false,
      treeProps: {
        children: "children", // 值是数据源上的属性
        label: "authName"
      },
      defKeys: [], // 某一个角色下所有的三级权限
      roleId:0
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status != 200) {
        return false;
      }
      this.rolelist = res.data;
    },
    async removeRightById(role, rightsId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      //   console.log(confirmResult)
      if (confirmResult == "cancel") {
        return this.$message.info("取消了删除");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightsId}`
      );
      //   console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除权限成功");
      // 把服务器返回的该角色下全新的权限列表赋值给这个角色的children属性
      role.children = res.data;
    },
    // 分配权限
    async showSettingRight(role) {
      this.roleId = role.id
      this.rightsDialogVisible = true;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status != 200) {
        return this.$message.error("加载权限列表失败");
      }
      this.rightslist = res.data;
      this.getDefKeys(role,this.defKeys)
    },
    // 获取角色下的三级权限
    // 参数1 角色对象
    // 参数2 数组
    // 递归就是函数在自己内容调用自己
    getDefKeys(node, arr) {
      //递归最重要的是结束条件
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => this.getDefKeys(item, arr));
    },
    resetDefKeys(){
        this.defKeys = []
    },
    async settingRights(){
        // 获取所有全选与半选的节点值也就是权限id
        // ... ES6的扩展运算符 就是展开数组 追加到新的数组中
        let rightsArr = [
            ...this.$refs.rightTreeRef.getCheckedKeys(),
            ...this.$refs.rightTreeRef.getHalfCheckedKeys()
        ]
        const { data:res } = await this.$http.post(`roles/${ this.roleId }/rights`,{ rids:rightsArr.join(',') })
        if(res.meta.status!=200){
            return this.$message.error('修改权限失败')
        }
        this.$message.success('修改成功')
        // 重新获取角色列表数据
        this.getRoleList()
        // 关闭弹窗
        this.rightsDialogVisible = false
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>